import json
import datetime
from package.connector.redis_db import rdb


class Cache:
    Prefix = ''


class UserCache(Cache):

    @staticmethod
    def user(item):
        return {
            'id': item.id,
            'name': item.name,
            'alias': item.alias,
            'roles': [{'name': role.name, 'permit': role.permit} for role in item.roles]
        }

    def get(self, key):
        if user := rdb.redis.get(f'{self.Prefix}:{key}'):
            return json.loads(user)

    def set(self, key, user, expired_at: int = None):
        """设置缓存"""
        value = json.dumps(self.user(user), ensure_ascii=False)
        if not expired_at:
            rdb.redis.set(f'{self.Prefix}:{key}', value)
            return
        ex = int(expired_at / 1000) - int(datetime.datetime.utcnow().timestamp())
        if ex <= 0:
            return
        rdb.redis.set(f'{self.Prefix}:{key}', value, ex=ex)

    def delete(self, key):
        rdb.redis.delete(f'{self.Prefix}:{key}')


class ApiKeyCache(UserCache):
    Prefix = 'system:apikey'


class AuthorizationCache(UserCache):
    Prefix = 'system:authorization'


class TokenCache(UserCache):
    Prefix = 'system:token'


apikey_cache = ApiKeyCache()
authorization_cache = AuthorizationCache()
token_cache = TokenCache()
